package com.yilife.kdys;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Helper {

	public static final byte[] md5(byte[] b) throws NoSuchAlgorithmException {
		MessageDigest mdInst = MessageDigest.getInstance("MD5");
		mdInst.update(b);
		return mdInst.digest();
	}

	public static final String md5(String content) {
		try {
			return bytesToHexStr(md5(content.getBytes("UTF8")));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static final String bytesToHexStr(byte[] b) {
		char[] chrs = new char[b.length * 2];
		for (int i = 0; i < b.length; ++i) {
			int i1 = 0xf & (b[i] >>> 4);
			int i2 = 0xf & (b[i]);
			chrs[i * 2] = HEX_CHAR[i1];
			chrs[i * 2 + 1] = HEX_CHAR[i2];
		}
		return new String(chrs);
	}
}
